﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace EarringsBackEnd
{
    public class ImageManagement
    {
        public void AutosizeImage(string ImagePath, PictureBox picBox, PictureBoxSizeMode pSizeMode = PictureBoxSizeMode.CenterImage)
        {
            try
            {
                picBox.Image = null;
                picBox.SizeMode = pSizeMode;
                if (System.IO.File.Exists(ImagePath))
                {
                    Bitmap imgOrg = default(Bitmap);
                    Bitmap imgShow = default(Bitmap);
                    Graphics g = default(Graphics);
                    double divideBy = 0;
                    double divideByH = 0;
                    double divideByW = 0;
                    imgOrg = (Bitmap)Bitmap.FromFile(ImagePath);

                    divideByW = imgOrg.Width / picBox.Width;
                    divideByH = imgOrg.Height / picBox.Height;
                    if (divideByW > 1 | divideByH > 1)
                    {
                        if (divideByW > divideByH)
                        {
                            divideBy = divideByW;
                        }
                        else
                        {
                            divideBy = divideByH;
                        }

                        imgShow = new Bitmap(Convert.ToInt32(Convert.ToDouble(imgOrg.Width) / divideBy), Convert.ToInt32(Convert.ToDouble(imgOrg.Height) / divideBy));
                        imgShow.SetResolution(imgOrg.HorizontalResolution, imgOrg.VerticalResolution);
                        g = Graphics.FromImage(imgShow);
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(imgOrg, new Rectangle(0, 0, Convert.ToInt32(Convert.ToDouble(imgOrg.Width) / divideBy), Convert.ToInt32(Convert.ToDouble(imgOrg.Height) / divideBy)), 0, 0, imgOrg.Width, imgOrg.Height, GraphicsUnit.Pixel);
                        g.Dispose();
                    }
                    else
                    {
                        imgShow = new Bitmap(imgOrg.Width, imgOrg.Height);
                        imgShow.SetResolution(imgOrg.HorizontalResolution, imgOrg.VerticalResolution);
                        g = Graphics.FromImage(imgShow);
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(imgOrg, new Rectangle(0, 0, imgOrg.Width, imgOrg.Height), 0, 0, imgOrg.Width, imgOrg.Height, GraphicsUnit.Pixel);
                        g.Dispose();
                    }
                    imgOrg.Dispose();

                    picBox.Image = imgShow;
                }
                else
                {
                    picBox.Image = null;
                }


            }
            catch (Exception ex)
            {
                //Interaction.MsgBox(ex.ToString());
            }

        }

        /// <summary>
        /// Method to resize, convert and save the image.
        /// </summary>
        /// <param name="image">Bitmap image.</param>
        /// <param name="maxWidth">resize width.</param>
        /// <param name="maxHeight">resize height.</param>
        /// <param name="quality">quality setting value.</param>
        /// <param name="filePath">file path.</param>      
        public void AutosizeImage(Bitmap image, int maxWidth, int maxHeight, int quality, string filePath)
        {
            // Get the image's original width and height
            int originalWidth = image.Width;
            int originalHeight = image.Height;

            // To preserve the aspect ratio
            float ratioX = (float)maxWidth / (float)originalWidth;
            float ratioY = (float)maxHeight / (float)originalHeight;
            float ratio = Math.Min(ratioX, ratioY);

            // New width and height based on aspect ratio
            int newWidth = (int)(originalWidth * ratio);
            int newHeight = (int)(originalHeight * ratio);

            // Convert other formats (including CMYK) to RGB.
            Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);

            // Draws the image in the specified size with quality mode set to HighQuality
            using (Graphics graphics = Graphics.FromImage(newImage))
            {
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.DrawImage(image, 0, 0, newWidth, newHeight);
            }

            // Get an ImageCodecInfo object that represents the JPEG codec.
            ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(ImageFormat.Jpeg);

            // Create an Encoder object for the Quality parameter.
            System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;

            // Create an EncoderParameters object. 
            EncoderParameters encoderParameters = new EncoderParameters(1);

            // Save the image as a JPEG file with quality level.
            EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
            encoderParameters.Param[0] = encoderParameter;
            newImage.Save(filePath, imageCodecInfo, encoderParameters);
        }

        /// <summary>
        /// Method to get encoder infor for given image format.
        /// </summary>
        /// <param name="format">Image format</param>
        /// <returns>image codec info.</returns>
        private ImageCodecInfo GetEncoderInfo(ImageFormat format)
        {
            return ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
        }
    }
}
